package com.liang.subject.domain.handler.subject;

import com.google.common.base.Preconditions;
import com.liang.subject.common.enums.SubjectInfoTypeEnum;
import com.liang.subject.domain.convert.MultipleSubjectConverter;
import com.liang.subject.domain.entity.SubjectAnswerBO;
import com.liang.subject.domain.entity.SubjectInfoBO;
import com.liang.subject.domain.entity.SubjectOptionBO;
import com.liang.subject.infra.basic.entity.SubjectMultiple;
import com.liang.subject.infra.basic.service.SubjectMultipleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 多选题目策略类
 */
@Component
@RequiredArgsConstructor
public class MultipleTypeHandler implements SubjectTypeHandler {

    private final SubjectMultipleService subjectMultipleService;

    @Override
    public SubjectInfoTypeEnum getSubjectType() {
        return SubjectInfoTypeEnum.MULTIPLE;
    }

    @Override
    public void save(SubjectInfoBO subjectInfoBO) {
        // 多选题目的插入
        List<SubjectAnswerBO> optionList = subjectInfoBO.getOptionList();
        Preconditions.checkNotNull(optionList, "题目选项不能为空");
        List<SubjectMultiple> multipleList = new ArrayList<>();
        optionList.forEach(option -> {
            SubjectMultiple subjectMultiple = MultipleSubjectConverter.INSTANCE.convertBO2PO(option);
            subjectMultiple.setSubjectId(subjectInfoBO.getId());
            multipleList.add(subjectMultiple);
        });
        subjectMultipleService.saveBatch(multipleList);
    }

    @Override
    public SubjectOptionBO querySubjectInfo(Long subjectId) {
        List<SubjectMultiple> multipleList = subjectMultipleService.listBySubjectId(subjectId);
        List<SubjectAnswerBO> subjectAnswerBOList = MultipleSubjectConverter.INSTANCE.convert2BOList(multipleList);
        SubjectOptionBO subjectOptionBO = new SubjectOptionBO();
        subjectOptionBO.setOptionList(subjectAnswerBOList);
        return subjectOptionBO;
    }
}
